<template>
  <div class="orderRev">
    <jc-button
      :btn-arr="['reload', 'newy', 'remove', 'option']"
      :disab-arr="['close', 'cancel', 'copy', 'freeze', 'com1', 'com2', 'chart']"
      @refresh="getUserList"
      @newly="newly"
      @toExcel="handleExport"
      @forbidden="using(1)"
      @startUsing="using(2)"
      @del="delCustom"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="searchMaterialList"
        />
        <el-button size="mini" type="primary" class="btn" @click="searchMaterialList">
          {{ $t('btn.search') }}
        </el-button>
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        table-selection
        @selectionChange="selectionDatas"
      >
        <template v-slot:billSlot="col">
          <el-link type="primary" @click="editSalType(col.scope.row)">{{ col.scope.row.fnumber }}</el-link>
        </template>
        <template v-slot:btnState="col">
          <el-tag
            v-if="col.scope.row.fstatedtl === 1"
            type="success"
          >
            {{ $t('market.consent') }}
          </el-tag>
          <el-tag v-else-if="col.scope.row.fstatedtl === 0" type="danger">{{ $t('market.consentNo') }}<!--禁用--></el-tag>
          <el-tag v-else-if="col.scope.row.fstatedtl === 2">{{ $t('market.state1') }}</el-tag>
        </template>
        <template v-slot:btnStates="col">
          <el-tag v-if="col.scope.row.fdefault===1">
            {{ $t('market.default') }}
          </el-tag>
        </template>
        <template v-slot:btnSlot="col">
          <el-button size="mini" type="warning" @click="editSalType(col.scope.row)">{{ $t('btn.edit') }}</el-button>
        </template>
      </jc-table>
    </div>
    <div class="footer">
      <jc-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="size"
        @pagination="getUserList"
      />
    </div>
    <!--单据审核-->
    <el-dialog
      v-dialog-drag
      :title="$t('menu.orderReview')"
      :visible.sync="addDialogVisible"
      width="800px"
      center
      top="5vh"
      :close-on-click-modal="false"
      :before-close="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        :model="addRole"
        size="mini"
        label-width="80px"
      >
        <el-form-item :label="$t('market.billType')">
          <el-select v-model="addRole.fbillTypeId" filterable>
            <el-option
              v-for="iten in staffDate"
              :key="iten.fid"
              :label="iten.fname"
              :value="iten.fid"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('market.default')">
          <el-radio-group v-model="addRole.fdefault">
            <el-radio :label="1">{{ $t('market.yes') }}</el-radio>
            <el-radio :label="0">{{ $t('market.no') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 5px;">
        <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
        <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
      </div>
      <div>
        <jc-table
          :table-data="tableData2"
          :table-header="tableHeader2"
          table-height="500px"
          serial
          @rowClick="rowClick"
        >
          <el-table-column :label="$t('market.approvalPro')" align="center" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.fname" filterable>
                <el-option
                  v-for="iten in staffDate1"
                  :key="iten.fdescripTion"
                  :label="iten.fname"
                  :value="iten.fdescripTion"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.approvUser')" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.fstaffid" multiple filterable style="width: 100%;">
                <el-option
                  v-for="item in options"
                  :key="item.fuserId"
                  :label="item.fname"
                  :value="item.fuserId"
                />
              </el-select>
            </template>
          </el-table-column>
        </jc-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addHandleClose">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="addRoleSubmit">{{ $t('btn.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryTShApprovalList,
  userstafftypeDisable,
  userstafftypeUnDisable,
  userslist,
  insertTShApproval,
  updateTShApproval,
  deleteTShApproval, getTShApprovalById
} from '@/api/basicManagement/userslist'
import search from '@/components/Search/index'
import searData from '@/components/Search/mixin'
import jcButton from '@/components/Button'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import { toMxAmina } from '@/components/ToMxamineState'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import { queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  components: {
    search,
    jcButton
  },
  mixins: [searData, autocomplete],
  data() {
    return {
      addDialogVisible: false,
      isDisabled: false,
      staffDate: [],
      staffDate1: [],
      addRole: {
        fuserid: 0,
        stafftype: ''
      },
      options: [], // 用户
      ftype: 76,
      fbillNo: 'fname',
      total: 0, // 总条目
      pageNum: 1, // 当前页
      size: 200, // 每页显示多少条数据
      tableData: [], // 列表数据
      // 表头数据
      tableHeader: [
        { label: this.$t('shop.fnumber'), type: 'bill', prop: 'fnumber', width: '120' },
        { label: '', prop: 'fnumberdesc', width: '120' },
        { label: this.$t('market.approvalPro'), prop: 'fname', width: '120' },
        { label: this.$t('shop.state'), type: 'state', prop: 'fstatedtl', width: '120' },
        { label: this.$t('market.default'), type: 'states', prop: 'fdefault', width: '120' },
        { label: this.$t('market.createtime'), prop: 'fcreatedate', width: '120' },
        { label: this.$t('shop.operation'), type: 'btn', width: '150' }
      ],
      tableData2: [],
      tableHeader2: [],
      tableHeader1: []
    }
  },
  created() {
    this.getUserList() // 列表
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 新增
    newly() {
      this.addDialogVisible = true
      this.queryBilType() // 单据类型
      this.queryBilType1() // 审批流程
      this.handleApplicant() // 审批流程
    },
    // 获取申请人
    async handleApplicant() {
      if (this.options.length > 0) return
      const { data: RES } = await userslist({
        formId: 'sec_user',
        pageNum: 1, // 当前页
        pageSize: 2000 // 每页显示多少条数据
      })
      const { array } = RES
      this.options = array
    },
    // 单据类型
    async queryBilType() {
      if (this.staffDate.length > 0) return
      const DATA = {
        viewName: 'SX_SH_APPROVAL'
      }
      const { data: RES } = await queryViewItem(DATA)
      this.staffDate = RES.list
    },
    // 审批流程
    async queryBilType1() {
      if (this.staffDate1.length > 0) return
      const DATA = {
        viewName: 'SPLC_PAREASON'
      }
      const { data: RES } = await queryViewItem(DATA)
      this.staffDate1 = RES.list
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '员工类型列表')
        } else {
          queryTShApprovalList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '员工类型列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectFbi }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.getUserList()
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 单据审核列表
    async getUserList() {
      this.loading = true
      const DATA = {
        pageNum: this.pageNum,
        pageSize: this.size,
        search: this.searCollData
      }
      const { data: res } = await queryTShApprovalList(DATA)
      this.tableData = res.array.map(item => {
        return (toMxAmina(item))
      })
      this.total = res.total
      this.loading = false
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.getUserList(ev.detail)
      } else {
        this.getUserList()
      }
    },
    selectionDatas(val) {
      this.selectFbi = []
      this.val = val
      this.val.forEach(res => {
        this.selectFbi.push(res.fid)
      })
    },
    // 禁用反禁用
    async using(ev) {
      const api = ev === 1 ? userstafftypeDisable : userstafftypeUnDisable
      this.toExamineFun(api)
    },
    // 删除员工类型
    delCustom() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = deleteTShApproval
        this.toExamineFun(api)
      })
    },
    // 新增员工类型 关闭前回调
    addHandleClose() {
      this.addRole = {}
      this.tableData2 = []
      this.addDialogVisible = false
    },
    // 修改
    editSalType(ev) {
      // 获取数据
      getTShApprovalById({ fid: ev.fid }).then(res => {
        if (res.code === 0) {
          this.addRole = res.data
          this.tableData2 = res.data.details
        }
      })
      this.newly()
    },
    // 新增|修改
    addRoleSubmit() {
      this.tableData2.map(res => {
        res.details = []
        res.fstaffid.forEach(item => {
          res.details.push({
            fstaffid: item,
            fentryid: res.fentryid
          })
        })
      })
      const DATA = {
        fbillTypeId: this.addRole.fbillTypeId,
        fid: this.addRole.fid,
        fdefault: this.addRole.fdefault,
        details: this.tableData2
      }
      const api = this.addRole.fid ? updateTShApproval : insertTShApproval
      api(DATA).then(res => {
        if (res.code === 0) {
          this.getUserList()
          this.addHandleClose()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      this.tableData2.push({
        fname: '',
        fstaffid: [],
        details: []
      })
    },
    // 删除行
    delHang() {
      this.tableData2.splice(this.indexSelf, 1)
    }
  }
}
</script>

<style scoped lang="scss">
.orderRev {
  @include listBom;
  .el-input .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      height: 35px;
      margin-bottom: 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
